<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->
<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-800">欢迎回来，{{ userEmail }}</h1>
    </div>
    <!-- 数据概览卡片 -->
    <div class="grid grid-cols-4 gap-6 mb-6">
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex items-center justify-between mb-4">
          <span class="text-gray-600">剩余积分</span>
          <el-icon class="text-yellow-500"><Medal /></el-icon>
        </div>
        <div class="text-2xl font-bold text-gray-800">{{ userStats.points }}</div>
      </div>
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex items-center justify-between mb-4">
          <span class="text-gray-600">会员到期</span>
          <el-icon class="text-indigo-500"><Calendar /></el-icon>
        </div>
        <div class="text-2xl font-bold text-gray-800">{{ userStats.membershipExpiry }}</div>
      </div>
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex items-center justify-between mb-4">
          <span class="text-gray-600">AI 对话次数</span>
          <el-icon class="text-green-500"><ChatDotRound /></el-icon>
        </div>
        <div class="text-2xl font-bold text-gray-800">{{ userStats.chatCount }}</div>
      </div>
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex items-center justify-between mb-4">
          <span class="text-gray-600">AI 绘图次数</span>
          <el-icon class="text-purple-500"><Picture /></el-icon>
        </div>
        <div class="text-2xl font-bold text-gray-800">{{ userStats.drawingCount }}</div>
      </div>
    </div>
    <!-- 图表区域 -->
    <div class="grid grid-cols-2 gap-6 mb-6">
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-medium text-gray-800">使用趋势</h2>
          <div class="flex space-x-2">
            <button
              class="px-3 py-1 text-sm rounded-full cursor-pointer whitespace-nowrap !rounded-button"
              :class="{
                'bg-blue-500 text-white': selectedPeriod === 7,
                'bg-gray-200 text-gray-700': selectedPeriod !== 7,
              }"
              @click="selectedPeriod = 7"
            >
              7 天
            </button>
            <button
              class="px-3 py-1 text-sm rounded-full cursor-pointer whitespace-nowrap !rounded-button"
              :class="{
                'bg-blue-500 text-white': selectedPeriod === 30,
                'bg-gray-200 text-gray-700': selectedPeriod !== 30,
              }"
              @click="selectedPeriod = 30"
            >
              30 天
            </button>
            <button
              class="px-3 py-1 text-sm rounded-full cursor-pointer whitespace-nowrap !rounded-button"
              :class="{
                'bg-blue-500 text-white': selectedPeriod === 90,
                'bg-gray-200 text-gray-700': selectedPeriod !== 90,
              }"
              @click="selectedPeriod = 90"
            >
              90 天
            </button>
          </div>
        </div>
        <div ref="usageChartRef" style="height: 300px"></div>
        <div class="flex justify-center mt-4 space-x-6">
          <div class="flex items-center">
            <div class="w-3 h-3 rounded-full bg-blue-500 mr-2"></div>
            <span class="text-sm text-gray-600">AI 对话 {{ usageSummary.chat }}</span>
          </div>
          <div class="flex items-center">
            <div class="w-3 h-3 rounded-full bg-green-500 mr-2"></div>
            <span class="text-sm text-gray-600">AI 绘图 {{ usageSummary.drawing }}</span>
          </div>
          <div class="flex items-center">
            <div class="w-3 h-3 rounded-full bg-yellow-500 mr-2"></div>
            <span class="text-sm text-gray-600">AI 视频 {{ usageSummary.video }}</span>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow p-6">
        <div class="mb-4">
          <h2 class="text-lg font-medium text-gray-800">功能使用占比</h2>
        </div>
        <div ref="usageRatioChartRef" style="height: 300px"></div>
      </div>
    </div>
    <!-- 订单和日历区域 -->
    <div class="grid grid-cols-2 gap-6">
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-medium text-gray-800">最近订单</h2>
          <button @click="goToOrder" class="text-blue-500 text-sm cursor-pointer whitespace-nowrap !rounded-button">
            查看全部
          </button>
        </div>
        <div class="overflow-x-auto">
          <table class="min-w-full">
            <thead>
              <tr class="border-b border-gray-200">
                <th class="py-3 text-left text-sm font-medium text-gray-500">订单名称</th>
                <th class="py-3 text-right text-sm font-medium text-gray-500">金额</th>
                <th class="py-3 text-right text-sm font-medium text-gray-500">状态</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="(order, index) in recentOrders"
                :key="index"
                class="border-b border-gray-200"
              >
                <td class="py-4">
                  <div class="text-sm font-medium text-gray-800">{{ order.name }}</div>
                  <div class="text-xs text-gray-500">{{ order.date }}</div>
                </td>
                <td class="py-4 text-right text-sm font-medium text-gray-800">
                  ¥ {{ order.amount.toFixed(2) }}
                </td>
                <td class="py-4 text-right">
                  <span
                    class="px-2 py-1 text-xs font-medium rounded-full bg-green-100 text-green-800"
                    >{{ order.status }}</span
                  >
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow p-6">
        <div class="mb-4">
          <h2 class="text-lg font-medium text-gray-800">签到日历</h2>
          <div class="text-sm text-gray-500">已连续签到 {{ consecutiveDays }} 天</div>
        </div>
        <div class="grid grid-cols-7 gap-2 mb-2 text-center">
          <div class="text-sm text-gray-500">一</div>
          <div class="text-sm text-gray-500">二</div>
          <div class="text-sm text-gray-500">三</div>
          <div class="text-sm text-gray-500">四</div>
          <div class="text-sm text-gray-500">五</div>
          <div class="text-sm text-gray-500">六</div>
          <div class="text-sm text-gray-500">日</div>
        </div>
        <div class="grid grid-cols-7 gap-2">
          <div v-for="day in calendarDays" :key="day.date" class="aspect-square">
            <button
              v-if="day.date !== 0"
              :class="[
                'w-full h-full flex items-center justify-center rounded-full text-sm cursor-pointer whitespace-nowrap !rounded-button',
                day.isToday ? 'bg-blue-500 text-white' : '',
                day.isCheckedIn && !day.isToday ? 'bg-green-100 text-green-800' : '',
                !day.isCheckedIn && !day.isToday ? 'hover:bg-gray-100' : '',
              ]"
            >
              {{ day.date }}
            </button>
          </div>
        </div>
        <div class="mt-4 text-right text-xs text-gray-500">Designed by Readdy</div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, watch } from 'vue'
import * as echarts from 'echarts'
import {
  User,
  Lock,
  Bell,
  ChatDotRound,
  Picture,
  VideoPlay,
  Medal,
  Star,
  ShoppingCart,
  List,
  Document,
  Upload,
  Calendar,
} from '@element-plus/icons-vue'
import { getUserConsumeData } from '@/api/ai'
import { ElMessage } from 'element-plus'
import { getUserInfo } from '@/utils/auth'
import {getRecentOrderService} from '@/api/order'
import { useRouter1 } from '../utils/useRoute'
import { formatDate } from '@/utils/dateFormat'
const {
  goToHome,
  goToDocumentUpload,
  goToKnowledgeBaseManagement,
  goToMemberCenter,
  goToNotificationSettings,
  goToOrder,
  goToPointsManagement,
  goToSecuritySettings,
  goToUser,
  goToAiChat,
  goToAiDrawing,
  goToProduct,
} = useRouter1()

// 获取用户信息
const userInfo = getUserInfo()
const userEmail = userInfo?.email || '未获取到邮箱'

// 用户数据
const username = ref('李明智')
const userStats = ref({
  points: 13580,
  membershipExpiry: '2025-06-30',
  chatCount: 1486,
  drawingCount: 352,
})
// 使用趋势图表
const usageChartRef = ref(null)
const usageRatioChartRef = ref(null)
let usageChart = null
let usageRatioChart = null
const selectedPeriod = ref(30)

// 加载状态
const loading = ref(false)

// 使用数据汇总
const usageSummary = ref({
  chat: 0,
  drawing: 0,
  video: 0,
})

// 获取使用数据
const fetchUsageData = async (days) => {
  loading.value = true
  try {
    const data = await getUserConsumeData(days)
    if (data && data.length > 0) {
      // 添加调试信息
      console.log('API返回的数据结构:', data[0])
      
      const chatData = []
      const drawingData = []
      const videoData = []
      const dateLabels = []
      
      // 计算总和
      let totalChat = 0
      let totalDrawing = 0
      let totalVideo = 0
      
      // 处理数据
      data.forEach(item => {
        dateLabels.push(item.dataDate.substring(5)) // 只显示月/日
        chatData.push(item.chatConsumeCount || 0)
        // 修复字段名 - 使用正确的大小写
        drawingData.push(item.drawConsumeCount || item.DrawConsumeCount || 0)
        videoData.push(item.videoConsumeCount || item.VideoConsumeCount || 0)
        
        // 累加总和
        totalChat += item.chatConsumeCount || 0
        totalDrawing += item.drawConsumeCount || item.DrawConsumeCount || 0
        totalVideo += item.videoConsumeCount || item.VideoConsumeCount || 0
      })
      
      console.log('处理后的数据:', { chatData, drawingData, videoData })
      
      // 更新汇总数据
      usageSummary.value = {
        chat: totalChat || 0,
        drawing: totalDrawing || 0,
        video: totalVideo || 0
      }
      
      // 更新图表
      updateUsageChart(dateLabels, chatData, drawingData, videoData)
    }
  } catch (error) {
    console.error('获取使用数据失败：', error)
    ElMessage.error('获取使用数据失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 更新使用趋势图表
const updateUsageChart = (dateLabels, chatData, drawingData, videoData) => {
  if (usageChartRef.value && usageChart) {
    const option = {
      animation: false,
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985',
          },
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dateLabels,
        axisLine: {
          lineStyle: {
            color: '#ddd',
          },
        },
        axisLabel: {
          color: '#666',
        },
      },
      yAxis: {
        type: 'value',
        min: 0,
        minInterval: 1,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: '#666',
        },
        splitLine: {
          lineStyle: {
            color: '#eee',
          },
        },
      },
      series: [
        {
          name: 'AI 对话',
          type: 'line',
          smooth: true,
          lineStyle: {
            width: 3,
            color: '#3b82f6',
          },
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#3b82f6',
          },
          data: chatData,
        },
        {
          name: 'AI 绘图',
          type: 'line',
          smooth: true,
          lineStyle: {
            width: 3,
            color: '#10b981',
            type: 'dashed',
          },
          symbol: 'rect',
          symbolSize: 8,
          itemStyle: {
            color: '#10b981',
          },
          data: drawingData,
        },
        {
          name: 'AI 视频',
          type: 'line',
          smooth: true,
          lineStyle: {
            width: 4,
            color: '#f59e0b',
            type: 'dotted',
          },
          symbol: 'triangle',
          symbolSize: 10,
          itemStyle: {
            color: '#f59e0b',
          },
          data: videoData,
        },
      ],
    }
    usageChart.setOption(option)
  }
}

// 初始化使用趋势图表
const initUsageChart = () => {
  if (usageChartRef.value) {
    usageChart = echarts.init(usageChartRef.value)
    // 初始化后立即获取数据
    fetchUsageData(selectedPeriod.value)
  }
}

// 初始化功能使用占比图表
const initUsageRatioChart = () => {
  if (usageRatioChartRef.value) {
    usageRatioChart = echarts.init(usageRatioChartRef.value)
    const option = {
      animation: false,
      tooltip: {
        trigger: 'item',
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        textStyle: {
          color: '#666',
        },
      },
      series: [
        {
          name: '功能使用占比',
          type: 'pie',
          radius: ['50%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: [
            { value: 45, name: 'AI 对话', itemStyle: { color: '#3b82f6' } },
            { value: 30, name: 'AI 绘图', itemStyle: { color: '#10b981' } },
            { value: 15, name: 'AI 视频', itemStyle: { color: '#f59e0b' } },
            { value: 10, name: 'AI 点评', itemStyle: { color: '#ef4444' } },
          ],
        },
      ],
    }
    usageRatioChart.setOption(option)
  }
}


// 监听窗口大小变化，重绘图表
window.addEventListener('resize', () => {
  usageChart?.resize()
  usageRatioChart?.resize()
})
// 监听选择的时间周期变化
const watchPeriodChange = () => {
  fetchUsageData(selectedPeriod.value)
}

const getRecentOrders=async()=>{
  const res=await getRecentOrderService()
  recentOrders.value=res.map(item=>{
    return{
      name:item.order.description,
      date:formatDate(item.order.payTime==null?item.order.createTime:item.order.payTime),
      amount:item.order.amount/100,
      status:item.order.status==1?'已支付':'未支付'
    }
    
  })
  console.log(res)
}
getRecentOrders()
// 最近订单数据
const recentOrders = ref([
  
])
// 签到日历数据
const consecutiveDays = ref(12)
// 生成当月日历数据
const calendarDays = computed(() => {
  const today = new Date()
  const currentMonth = today.getMonth()
  const currentYear = today.getFullYear()
  // 获取当月第一天是星期几
  const firstDay = new Date(currentYear, currentMonth, 1).getDay() || 7 // 转换为周一为1
  // 获取当月天数
  const lastDate = new Date(currentYear, currentMonth + 1, 0).getDate()
  const days = []
  // 填充前面的空白
  for (let i = 1; i < firstDay; i++) {
    days.push({ date: 0, isToday: false, isCheckedIn: false })
  }
  // 填充日期
  for (let i = 1; i <= lastDate; i++) {
    const isToday = i === today.getDate()
    const isCheckedIn = i <= today.getDate() // 假设今天之前的日期都已签到
    days.push({
      date: i,
      isToday,
      isCheckedIn,
    })
  }
  return days
})
// 页面加载时初始化图表
onMounted(() => {
  initUsageChart()
  initUsageRatioChart()
})
// 监听周期变化
watch(selectedPeriod, watchPeriodChange)
</script>
<style scoped>
.aspect-square {
  aspect-ratio: 1 / 1;
}
:deep(.el-icon) {
  font-size: 1.25rem;
}
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>
